package com.xsq.netty;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;

import androidx.annotation.NonNull;

import com.google.gson.JsonObject;
import com.xsq.netty.channel.INettyChannelListener;
import com.xsq.netty.utils.LogUtils;

import java.io.IOException;

/**
 * Created by Shiquan.Xiao on 2023/2/23.
 */
public class NettyHelper {

    public static final String TAG = "RSNettyClient";
    private static volatile NettyHelper instance;
    private volatile static boolean hasInit = false;
    private static INettyService iNettyService;
    private static IServiceListener listener;
    //初始连接
    public static final int INITIAL_CONNECTION = 1;
    //设备建立连接成功
    public static final int DEVICE_ON = 2;
    // 心跳
    public static final int HEART_BEAT = 3;
    // 人脸识别
    public static final int MSG_TYPE_FACE_REGISTER = 4;
    //推送ip
    public static final int LOCAL_IP_ADDRESS = 5;
    //卡片信息
    public static final int CARD_INFO = 6;
    //推送设备开门
    public static final int DEVICE_OPEN_DOOR = 7;
    //设备信息变更
    public static final int MSG_TYPE_DEVICE_INFO_CHANGE = 8;
    //卡片更新
    public static final int CARD_UPDATE = 11;
    //卡片删除
    public static final int CARD_DELETE = 12;
    //项目信息变更
    public static final int PROJECT_INFO_CHANGE = 13;
    //告警信息
    public static final int MSG_PUSH_SECURITY_ALARM_INFO = 18;
    public static final int MSG_TYPE_REPORT_NETWORK = 100;
    //设备没激活
    public static final int MSG_TYPE_UN_ACTIVATION = 101;
    //设备已激活
    public static final int MSG_TYPE_ACTIVATED = 102;
    public static final int MSG_TYPE = 0xAB;
    public static final int MSG_FLAG = 0xCD;

    private NettyHelper() {
    }

    public static void init(Context context, @NonNull NettyConfig config) {
        if (!hasInit) {
            hasInit = NettyClient.getInstance().init(context, config);
            if (hasInit) {
                initialization(context, config);
            }
        }
    }

    private static void initialization(Context context, NettyConfig config) {
        Intent intent = new Intent("com.rishun.netty.SERVICE_INITIALIZATION");
        intent.setPackage(config.servicePackageName);
        context.getApplicationContext().bindService(intent, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                iNettyService = INettyService.Stub.asInterface(service);
                if (iNettyService != null && listener != null) {
                    listener.onBindService(iNettyService);
                }
                if (config.isService && config.isAutoConnect && iNettyService != null) {
                    NettyClient.getInstance().connect();
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
            }
        }, Context.BIND_AUTO_CREATE);
    }

    public static void rebind(Context context) {
        Intent intent = new Intent("com.rishun.netty.SERVICE_INITIALIZATION");
        NettyConfig nettyConfig = NettyClient.getInstance().nettyConfig();
        intent.setPackage(nettyConfig.servicePackageName);
        context.getApplicationContext().bindService(intent, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                iNettyService = INettyService.Stub.asInterface(service);
                if (iNettyService != null && listener != null) {
                    listener.onBindService(iNettyService);
                }
                if (nettyConfig.isService && nettyConfig.isAutoConnect && iNettyService != null) {
                    NettyClient.getInstance().connect();
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
            }
        }, Context.BIND_AUTO_CREATE);
    }

    public static NettyHelper getInstance() {
        if (null == instance) {
            synchronized (NettyHelper.class) {
                if (null == instance) {
                    instance = new NettyHelper();
                }
            }
        }

        return instance;
    }

    public void addRemoteNettyListener(IBinder iBinder) {
        if (iNettyService == null) {
            LogUtils.e(TAG, "没有绑定服务");
            return;
        }
        Intent intent1 = new Intent();
        try {
            Bundle bundle = new Bundle();
            bundle.putInt("invoking_code", 1000);
            bundle.putBinder("binder_netty_listener", iBinder);
            intent1.putExtra("extra_bundle",bundle);
            iNettyService.sendData(intent1);
        } catch (RemoteException e) {
            LogUtils.e(NettyHelper.TAG, "addINettyListener: "+e.getMessage());
        }
    }

    public void removeRemoteNettyListener(IBinder iBinder) {
        if (iNettyService == null) {
            LogUtils.e(TAG, "没有绑定服务");
            return;
        }
        Intent intent1 = new Intent();
        try {
            Bundle bundle = new Bundle();
            bundle.putInt("invoking_code", -1000);
            bundle.putBinder("binder_netty_listener", iBinder);
            intent1.putExtra("extra_bundle",bundle);
            iNettyService.sendData(intent1);
        } catch (RemoteException e) {
            LogUtils.e(NettyHelper.TAG, "addINettyListener: "+e.getMessage());
        }
    }


    /**
     * 发送消息
     */
    public void sendMessage(JsonObject msg) {
        if (iNettyService == null) {
            LogUtils.e(TAG, "没有绑定服务");
            return;
        }
        if (msg == null) {
            LogUtils.e(TAG, "发送的消息为空，sendMessage(msg)方法不支持空消息!");
            return;
        }

        try {
            iNettyService.sendMessage(msg.toString());
        } catch (RemoteException e) {
            LogUtils.e(NettyHelper.TAG, "sendMessage: "+e.getMessage());
        }
    }

    public void sendMessage(String msg) {
        if (iNettyService == null) {
            LogUtils.e(TAG, "没有绑定服务");
            return;
        }
        if (msg == null) {
            LogUtils.e(TAG, "发送的消息为空，sendMessage(msg)方法不支持空消息!");
            return;
        }

        try {
            iNettyService.sendMessage(msg);
        } catch (RemoteException e) {
            LogUtils.e(NettyHelper.TAG, "sendMessage: "+e.getMessage());
        }
    }

    public void setHeartbeatMsg(String msg) {
        if (iNettyService == null) {
            LogUtils.e(TAG, "没有绑定服务");
            return;
        }
        try {
            iNettyService.setHeartbeatMsg(msg);
        } catch (RemoteException e) {
            LogUtils.e(NettyHelper.TAG, "setHeartbeatMsg: "+e.getMessage());
        }
    }

    public void connect() {
        if (iNettyService == null) {
            LogUtils.e(TAG, "没有绑定服务");
            return;
        }
        try {
            iNettyService.connect();
        } catch (RemoteException e) {
            LogUtils.e(NettyHelper.TAG, "connect: "+e.getMessage());
        }
    }

    public boolean isBinding() {
        if (iNettyService == null) {
            LogUtils.e(TAG, "没有绑定服务");
            return false;
        }
        return iNettyService.asBinder().pingBinder();
    }

    public boolean isAutoConnect() {
        if (iNettyService == null) {
            LogUtils.e(TAG, "没有绑定服务");
            return false;
        }
        return NettyClient.getInstance().nettyConfig().isAutoConnect;
    }

    public boolean isConnected() {
        if (iNettyService == null) {
            LogUtils.e(TAG, "没有绑定服务");
            return false;
        }
        try {
            return iNettyService.isConnected();
        } catch (RemoteException e) {
            return false;
        }
    }

    public boolean haveConnection() {
        if (iNettyService == null) {
            LogUtils.e(TAG, "没有绑定服务");
            return false;
        }
        try {
            return iNettyService.hasConnection();
        } catch (RemoteException e) {
            return false;
        }
    }

    public static void setNettyServiceListener(IServiceListener listener) {
        NettyHelper.listener = listener;
    }

    public void setListener(INettyChannelListener listener) {
        NettyClient.getInstance().setListener(listener);
    }

    public void addNettyListener(IBinder listener) {
        NettyClient.getInstance().addNettyListener(listener);
    }

    public void removeNettyListener(IBinder listener) {
        NettyClient.getInstance().removeNettyListener(listener);
    }

    public void closeConnect(){
        NettyClient.getInstance().closeConnect();
    }

    public void release(){
        try {
            NettyClient.getInstance().release();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void closeConnection() {
        NettyClient.getInstance().closeConnection();
    }



}
